package com.zb.rpc.client.netty;

import com.zb.rpc.client.AbstractRpcClient;
import com.zb.rpc.client.RpcClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class NettyClient extends AbstractRpcClient {

    private Bootstrap bootstrap;

    private volatile Channel channel;

    private static final NioEventLoopGroup NIO_GROUP = new NioEventLoopGroup();

    public NettyClient(String hostName, int port, int connectionTimeout) {
        try {
            bootstrap = new Bootstrap();
            bootstrap
                    .group(NIO_GROUP)
                    .remoteAddress("127.0.0.1", 8080)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // 每隔60s的时间触发一次userEventTriggered的方法，并且指定IdleState的状态位是WRITER_IDLE,事件触发给服务器发送ping消息
                                    .addLast("idle", new IdleStateHandler(0, 60, 0, TimeUnit.SECONDS))
                                    // 添加解码器
                                    .addLast(new StringDecoder())
                                    // 添加编码器
                                    .addLast(new StringEncoder())
                                    // 添加消息处理器
                                    .addLast("messageHandler", new MessageHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect().sync();
            channel = channelFuture.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            NIO_GROUP.shutdownGracefully();
        }

    }

    public void invoke0(Object data) {
        channel.writeAndFlush();
    }

}
